<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>壁纸上传测试</title>
</head>
<body>
<h2>壁纸上传接口测试</h2>
<!-- 登录表单 -->
<form id="loginForm">
    <label>用户名:
        <input type="text" id="login-username" required>
    </label><br><br>
    <label>密码:
        <input type="password" id="login-password" required>
    </label><br><br>
    <button type="submit">登录</button>
</form>
<pre id="loginResult"></pre>
<br>
<form id="uploadForm" enctype="multipart/form-data">
    <label>选择图片文件:
        <input type="file" name="file" required>
    </label><br><br>
    <label>标题:
        <input type="text" id="title" required>
    </label><br><br>
    <label>描述:
        <input type="text" id="desc">
    </label><br><br>
    <label>Token:
        <input type="text" id="token" placeholder="Bearer ..." required style="width:400px">
    </label><br><br>
    <button type="submit">上传</button>
</form>
<pre id="result"></pre>
<script>
    // 登录表单提交
    document.getElementById('loginForm').onsubmit = async function(e) {
        e.preventDefault();
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;
        const res = await fetch('http://localhost:8080/api/v1/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        const data = await res.json();
        console.log('登录返回：', data); // 调试输出
        // 自动识别常见 token 字段
        let token = data.token || data.accessToken || data.jwt || (data.data && data.data.token);
        if (res.ok && token) {
            document.getElementById('token').value = 'Bearer ' + token;
            document.getElementById('loginResult').textContent = '登录成功';
        } else {
            document.getElementById('loginResult').textContent = '登录失败: ' + (data.message || res.status);
        }
    };
    // 上传表单提交
    document.getElementById('uploadForm').onsubmit = async function(e) {
        e.preventDefault();
        const form = new FormData();
        const fileInput = document.querySelector('input[name="file"]');
        form.append('file', fileInput.files[0]);
        const wallpaperUploadDAO = {
            title: document.getElementById('title').value,
            description: document.getElementById('desc').value
        };
        form.append('wallpaperUploadDAO', JSON.stringify(wallpaperUploadDAO));
        const token = document.getElementById('token').value;
        const res = await fetch('http://localhost:8080/api/v1/wallpapers/upload', {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: form
        });
        const text = await res.text();
        document.getElementById('result').textContent = text;
    };
</script>
</body>
</html>
